package com.sms.controller;

import cn.hutool.json.JSONUtil;
import com.sms.common.A;
import com.sms.pojo.Users;
import com.sms.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//修改密码
@WebServlet("/UsersModifyPassword")
public class UsersModifyPasswordController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("username");
        String password = req.getParameter("password");
        String newPassword = req.getParameter("newPassword");
        String confirmPassword = req.getParameter("confirmPassword");

        if (username == null || username.isEmpty()) {
            resp.getWriter().write(JSONUtil.toJsonStr(A.fail("用户名不能为空")));
        }

        if (password == null || password.isEmpty()) {
            resp.getWriter().write(JSONUtil.toJsonStr(A.fail("密码不能为空")));
        }

        if (!newPassword.equals(confirmPassword)) {
            resp.getWriter().write(JSONUtil.toJsonStr((A.fail("两次输入的密码不一致"))));
        }

        UsersServiceImpl impl=new UsersServiceImpl();
        Users user;
        if(impl.modifyPassword(username,password)){
            user=impl.findByUsernameAndPassword(username,password);
            impl.getSqlSession().close();
            user.setPassword(newPassword);
            impl.updateById(user);
            impl.getSqlSession().close();
            resp.getWriter().write(JSONUtil.toJsonStr(A.success("修改成功")));
        } else {
            impl.getSqlSession().close();
            resp.getWriter().write(JSONUtil.toJsonStr(A.fail("修改失败")));

        }

    }
}
